package com.jit.monitor.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.xrecyclerview.XRecyclerView;
import com.jit.baselib.baseapp.AppManager;
import com.jit.baselib.ui.base.BaseActivity;
import com.jit.baselib.util.PerfectClickListener;
import com.jit.baselib.util.ui.ResHelper;
import com.jit.baselib.util.ui.UIUtils;
import com.jit.baselib.util.window.DisplayHelper;
import com.jit.monitor.R;
import com.jit.monitor.commom.AppConstant;
import com.jit.monitor.model.bean.AlarmBean;
import com.jit.monitor.model.bean.AlarmRangeBean;
import com.jit.monitor.model.cache.UserCache;
import com.jit.monitor.model.request.WarnRequest;
import com.jit.monitor.model.response.MainResponse;
import com.jit.monitor.presenter.MainAtPresenter;
import com.jit.monitor.ui.WarnAreaActivity;
import com.jit.monitor.ui.activity.user.LoginActivity;
import com.jit.monitor.ui.activity.user.RestPwdActivity;
import com.jit.monitor.ui.adapter.AlarmAdapter;
import com.jit.monitor.ui.adapter.AlarmRangAdapter;
import com.jit.monitor.ui.adapter.part.MainListPartAdapter;
import com.jit.monitor.ui.photos.PullPhotoDetailActivity;
import com.jit.monitor.util.BuglyHelper;
import com.jit.monitor.view.MainAtView;
import com.jit.monitor.widget.BottomDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import static com.jit.monitor.ui.adapter.part.MainListPartAdapter.JUST_REFRESH_NAME;


/**
 * @author zxl on 2018/06/30.
 * discription: shift + F
 */

public class MainActivity extends BaseActivity<MainAtView,MainAtPresenter> implements MainAtView, MainListPartAdapter.MainListListener {
    @BindView(R.id.view_status)
    View mViewStatus;
    @BindView(R.id.iv_avatar)
    ImageView mIvAvatar;
    @BindView(R.id.tv_username)
    TextView mTvUsername;
    @BindView(R.id.ll_header_bg)
    LinearLayout mLlHeaderBg;
    @BindView(R.id.ll_nav_homepage)
    LinearLayout mLlNavHomepage;
    @BindView(R.id.ll_nav_change)
    LinearLayout mLlNavChange;
    @BindView(R.id.ll_ring)
    LinearLayout mLlRing;
    @BindView(R.id.line)
    View mLine;
    @BindView(R.id.ll_nav_logout)
    LinearLayout mLlNavLogout;
    @BindView(R.id.ll_nav_exit)
    LinearLayout mLlNavExit;
    @BindView(R.id.ll_nav_area)
    LinearLayout mLlRingArea;
    @BindView(R.id.nav_view)
    NavigationView mNavView;
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.iv_title_menu)
    ImageView mIvTitleMenu;
    @BindView(R.id.ll_title_menu)
    FrameLayout mLlTitleMenu;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.recHome)
    XRecyclerView mXRecyclerView;
    @BindView(R.id.tvNoData)
    TextView tvNoData;
    @BindView(R.id.fmContent)
    FrameLayout mContent;
    @BindView(R.id.ll_error_refresh)
    LinearLayout mRefresh;
    @BindView(R.id.ll_progress_bar)
    LinearLayout mLlProgressBar;
    @BindView(R.id.img_progress)
    ImageView mIvProgress;


    private MainListPartAdapter mMainListAdapter;
    private List<MainResponse> mMainResponseList = new ArrayList<>();
    private boolean mIsFirst = true;
    private boolean canUpdate = true;
    private List<AlarmBean> mAlarmBeans = new ArrayList<>();
    private Timer mTimer;
    /**
     * 选择预警的Dialog
     */
    private BottomDialog mChooseAlarmDialog;
    /**
     * 用于保存当前获取页
     */
    private int mPage = 1;
    private RecyclerView mAlarmRecyclerView;
    private AlarmAdapter mAlarmAdapter;
    private AnimationDrawable mAnimationDrawable;
    private boolean isCreate = false;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("com.jit.monitor.refreshUI".equals(action)){
                if (mLoadingListener != null) {
                    // 进行了刷新了
                    mXRecyclerView.doHandRefresh();
                }
            }
        }
    };
    private XRecyclerView.LoadingListener mLoadingListener;
    private LinearLayoutManager mLinearLayoutManager;

    private void registerBroadCast(){
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.jit.monitor.refreshUI");
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void init() {
        Log.e("token", UserCache.getUserToken());
        Log.e("token id", UserCache.getUserID()+"");

        mAlarmBeans.add(new AlarmBean(1,"震动",R.drawable.ic_vb,false));
        mAlarmBeans.add(new AlarmBean(2,"铃声",R.drawable.ic_sound,false));
        mAlarmBeans.add(new AlarmBean(4,"普通通知",R.drawable.ic_notification,false));
    }

    /**
     * 跳转向MainActivity
     *
     * @param context
     */
    public static void show(Activity context) {
        context.startActivity(new Intent(context, MainActivity.class));
        context.overridePendingTransition(R.anim.screen_zoom_in, R.anim.screen_zoom_out);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected MainAtPresenter createPresenter() {
        return new MainAtPresenter(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.e("JPUSH", "onNewIntent: 执行了" );
        mPresenter.queryList(mPage);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 这是可有可无的 因为是gone掉了
        initStatusBar();
        DisplayHelper.setColorNoTranslucentForDrawerLayout(MainActivity.this, mDrawerLayout,
                ResHelper.getColor(R.color.colorAPPPrimary));
        initDrawerLayout();
        initRecyclerView();
        // 加载动画
        mAnimationDrawable = (AnimationDrawable) mIvProgress.getDrawable();
        // 默认进入页面就开启动画
        if (!mAnimationDrawable.isRunning()) {
            mAnimationDrawable.start();
        }
        mContent.setVisibility(View.GONE);
        // 从通知栏传递 如果已经刷新了那么直接刷新页面
        registerBroadCast();
        mTimer = new Timer();
        // 延迟1分钟 每隔1分钟刷新
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                UIUtils.postTaskSafely(new Runnable() {
                    @Override
                    public void run() {
                        showLoading();
                    }
                });
                UIUtils.postTaskDelay(new Runnable() {
                    @Override
                    public void run() {
                        mXRecyclerView.doHandRefresh();
                    }
                },1000*3);
            }
        },1000*60,1000*60);
    }

    /**
     * 初始化recyclerView
     */
    private void initRecyclerView() {
        mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mXRecyclerView.setLayoutManager(mLinearLayoutManager);
        mMainListAdapter = new MainListPartAdapter(MainActivity.this,mMainResponseList,this);
        mXRecyclerView.setAdapter(mMainListAdapter);
        //设置的刷新
        mLoadingListener = new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //设置的刷新
                mPage = 1;
                mPresenter.queryList(mPage);
            }

            @Override
            public void onLoadMore() {
                mPage++;
                mPresenter.queryList(mPage);
            }
        };
        mXRecyclerView.setLoadingListener(mLoadingListener);
    }


    private void initStatusBar() {
        ViewGroup.LayoutParams layoutParams = mViewStatus.getLayoutParams();
        layoutParams.height = DisplayHelper.getStatusBarHeight(this);
        mViewStatus.setLayoutParams(layoutParams);
    }

    private void updateApp() {
        if (canUpdate) {
            BuglyHelper.getInstance().doUpdateNow(this);
            canUpdate = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mReceiver != null) {
            unregisterReceiver(mReceiver);
        }

        if (mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }
    }


    /**
     * inflateHeaderView 进来的布局要宽一些
     */
    private void initDrawerLayout() {
        mLlNavHomepage.setOnClickListener(mPerfectClickListener);
        mLlRing.setOnClickListener(mPerfectClickListener);
        mLlNavChange.setOnClickListener(mPerfectClickListener);
        mLlNavExit.setOnClickListener(mPerfectClickListener);
        mLlNavLogout.setOnClickListener(mPerfectClickListener);
        mLlRingArea.setOnClickListener(mPerfectClickListener);
    }

    /**
     * 加载数据
     */
    @Override
    protected void initData() {
        mPresenter.queryList(mPage);
        isCreate = true;
    }

    @Override
    protected void initListener() {
        mIvTitleMenu.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mDrawerLayout.openDrawer(GravityCompat.START);
            }
        });

        mRefresh.setOnClickListener(v -> initData());
    }

    private void editCameraName(int position, String cameraID,String name) {
        EditCmNameActivity.showCameraNameActivity(this,position,cameraID,name);
    }

    private PerfectClickListener mPerfectClickListener = new PerfectClickListener() {
        @Override
        protected void onNoDoubleClick(View v) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
            mDrawerLayout.postDelayed(() -> {
                switch (v.getId()) {
                    case R.id.ll_ring:
                        // 直接执行查询
                        mPresenter.queryType();
                        break;
                    case R.id.ll_nav_change:
                        jumpToActivity(RestPwdActivity.class);
                        break;
                    case R.id.ll_nav_exit:
                        AppManager.getAppManager().finishAllActivity();
                        break;
                    case R.id.ll_nav_homepage:
                        break;
                    case R.id.ll_nav_logout:
                        mPresenter.doLogout();
                        break;
                    case R.id.ll_nav_area:
                        jumpToActivity(WarnAreaActivity.class);
                        break;
                    default:
                        break;
                }
            }, 260);
        }
    };


    @Override
    public void logoutSuccess() {
        AppManager.getAppManager().finishAllActivity();
        jumpToActivityAndClearTask(LoginActivity.class);
    }

    @Override
    public void logoutFailure() {
        Toast.makeText(mContext, "退出登陆失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void queryListSuccess(List<MainResponse> list) {
        showContentView();
        if (mIsFirst){
            if (list != null) {
                mMainResponseList.clear();
                mMainResponseList.addAll(list);
                mMainListAdapter.notifyDataSetChanged();
            }
            mIsFirst = false;

        }else {
            if (mPage == 1){
                mMainResponseList.clear();
                mMainResponseList.addAll(list);
                mMainListAdapter.notifyDataSetChanged();
                // 刷新成功
                mXRecyclerView.refreshComplete();
                if (mMainResponseList.size() > 0){
                    mXRecyclerView.scrollToPosition(0);
                    mLinearLayoutManager.scrollToPositionWithOffset(0,0);
                }
            }else {
                if (list != null && list.size() > 0){
                    mMainResponseList.addAll(list);
                    mMainListAdapter.notifyDataSetChanged();
                    mXRecyclerView.refreshComplete();
                }else {
                    mXRecyclerView.noMoreLoading();
                }
            }
        }


        if (mMainResponseList == null || mMainResponseList.size() == 0){
            tvNoData.setVisibility(View.VISIBLE);
        }else {
            tvNoData.setVisibility(View.GONE);
        }
        updateApp();
    }

    @Override
    public void queryListFailure(String msg) {
        UIUtils.showToast(msg);
        mXRecyclerView.refreshComplete();
        if (mIsFirst){
            mIsFirst = false;
        }
        showError();

        if (mPage > 1) {
            mPage--;
        }
        updateApp();
    }

    /**
     * 查询类型------
     * @param type
     */
    @Override
    public void queryTypeSuccess(int type) {
        if (type != AppConstant.NOTIFICATION_TYPE){
           // 只有不是该类型那么才进行设置为true的操作
           for (int i =0 ;i<mAlarmBeans.size();i++){
               AlarmBean alarmBean = mAlarmBeans.get(i);
               if (alarmBean.getType() == type){
                   alarmBean.setState(true);
               }else {
                   alarmBean.setState(false);
               }
           }
        }
        showSheetDialog();
    }

    @Override
    public void queryTypeFailure(String error) {
        UIUtils.showToast("获取预警铃声出错:"+error);
    }




    @Override
    public void setTypeSuccess(int type,String name) {
        UIUtils.showToast("成功设置警报铃声为:"+name);
    }

    @Override
    public void setTypeFailure(String msg) {
        UIUtils.showToast("设置警报铃声失败:"+msg);
    }

    @Override
    public void controlNotifySuccess(String msg) {
        UIUtils.showToast(msg);
    }

    @Override
    public void controlNotifyFailure(int position, String state, String error) {
        UIUtils.showToast(error);
        mMainResponseList.get(position).getCamera().setEnableNotification(state.equals(AppConstant.NOTIFY_WITH_LED_OFF)?AppConstant.NOTIFY_WITH_LED_ON:AppConstant.NOTIFY_WITH_LED_OFF);
        mMainListAdapter.notifyItemChanged(position+1,MainListPartAdapter.JUST_REFRESH_SWITCH_BUTTON);
    }

    @Override
    public void controlLedSuccess(int position, String msg) {
        // 进行刷新
        Log.e("light", "controlLedSuccess: "+position );
        UIUtils.showToast(msg);
        mMainResponseList.get(position).getCamera().setLedFlag(AppConstant.NOTIFY_WITH_LED_OFF);
        mMainListAdapter.notifyItemChanged(position+1);
        //mMainListAdapter.notifyItemChanged(position,MainListPartAdapter.JUST_REFRESH_LIGHT);
        Log.e("light", "后面执行刷新" );
    }

    @Override
    public void controlLedFailure(int position, String error) {
        // 提醒失败
        UIUtils.showToast(error);
        UIUtils.showToast("操作失败,请检查后重试");
    }



    /**
     * Tag 选择 ------
     * @param frameID
     * @param objDetType
     */
    @Override
    public void onDetSelected(String frameID, String objDetType) {
        CurrentDetailActivity.showCurrentDetailInfo(this,frameID,objDetType);
    }

    @Override
    public void onImageSelected(ImageView imageView, String url) {
        PullPhotoDetailActivity.startAction(MainActivity.this,url, imageView);
    }

    @Override
    public void onEditSelected(int position, String text,String frameID) {
        Log.e("编辑", "onEditSelected: "+position+"------"+text+"  "+frameID);
        editCameraName(position,frameID,text );
    }

    @Override
    public void onNumberClick(String ID) {
        showMaterialDialog("帧信息编号详情", ID, "", "取消", null, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onSwitchButtonOnCheck(int position, boolean state, String cameraID, String cameraName) {
        String flag = state ?AppConstant.NOTIFY_WITH_LED_ON:AppConstant.NOTIFY_WITH_LED_OFF;
        mPresenter.userControlCamera(position,cameraName,cameraID,flag);
    }

    @Override
    public void onISeeClicked(int position, String cameraID) {
        mPresenter.userControlLed(position,cameraID);
    }

    @Override
    public void onHistoryClicked(String cameraID, String cameraName) {
        Log.e("点击", "onHistoryClicked: "+cameraID+"  "+cameraName );
        WarnHistoryActivity.startAction(this,cameraID,cameraName);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case AppConstant.RECODE_FROM_MAIN_TO_CM:
                    reChangeCameraName(data.getStringExtra(AppConstant.CAMERANAME),data.getIntExtra(AppConstant.CAMERA_INDEX,0));
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 展开底部的Dialog 这种Dialog效果真的好
     */
    private void showSheetDialog() {
        mChooseAlarmDialog = new BottomDialog(this,0,true);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_alarm, null, false);
        mAlarmRecyclerView = view.findViewById(R.id.alarmRecycler);
        initAlarmRecyclerView();
        mChooseAlarmDialog.setContentView(view);
        // 设置背景为透明色 那么白色的就能呈现出来了
        mChooseAlarmDialog.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet)
                .setBackgroundColor(getResources().getColor(android.R.color.transparent));

        mChooseAlarmDialog.show();
    }

    /**
     * 初始化RecyclerView
     */
    private void initAlarmRecyclerView() {
        mAlarmRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        mAlarmAdapter = new AlarmAdapter(R.layout.item_alarm_type, mAlarmBeans);
        mAlarmRecyclerView.setAdapter(mAlarmAdapter);
        mAlarmAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mAlarmBeans.get(position).isState()){
                    Toast.makeText(mContext, "当前预警铃声已是"+mAlarmBeans.get(position).getType(), Toast.LENGTH_SHORT).show();
                }else {
                    mPresenter.setAlarmType(mAlarmBeans.get(position).getType(),mAlarmBeans.get(position).getName());
                }
                mChooseAlarmDialog.dismiss();
            }
        });
    }


    private void reChangeCameraName(String cameraName,int index) {
        mMainResponseList.get(index).getCamera().setName(cameraName);
        Log.e("刷新", Thread.currentThread().getName());
        mMainListAdapter.notifyItemChanged(index+1,JUST_REFRESH_NAME);
    }


    /**
     * 显示加载中状态
     */
    protected void showLoading() {
        if (mLlProgressBar.getVisibility() != View.VISIBLE) {
            mLlProgressBar.setVisibility(View.VISIBLE);
        }
        // 开始动画
        if (!mAnimationDrawable.isRunning()) {
            mAnimationDrawable.start();
        }
        if (mContent.getVisibility() != View.GONE) {
            mContent.setVisibility(View.GONE);
        }
        if (mRefresh.getVisibility() != View.GONE) {
            mRefresh.setVisibility(View.GONE);
        }
    }

    /**
     * 加载完成的状态
     */
    protected void showContentView() {
        if (mLlProgressBar.getVisibility() != View.GONE) {
            mLlProgressBar.setVisibility(View.GONE);
        }
        // 停止动画
        if (mAnimationDrawable.isRunning()) {
            mAnimationDrawable.stop();
        }
        if (mRefresh.getVisibility() != View.GONE) {
            mRefresh.setVisibility(View.GONE);
        }
        if (mContent.getVisibility() != View.VISIBLE) {
            mContent.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 加载失败点击重新加载的状态
     */
    protected void showError() {
        if (mLlProgressBar.getVisibility() != View.GONE) {
            mLlProgressBar.setVisibility(View.GONE);
        }
        // 停止动画
        if (mAnimationDrawable.isRunning()) {
            mAnimationDrawable.stop();
        }
        if (mRefresh.getVisibility() != View.VISIBLE) {
            mRefresh.setVisibility(View.VISIBLE);
        }
        if (mContent.getVisibility() != View.GONE) {
            mContent.setVisibility(View.GONE);
        }
    }
}
